package com.wan.net.core.client;

import com.wan.core.shutdown.ShutdownManager;
import com.wan.net.config.HostAndPort;
import com.wan.net.core.packet.Packet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wwh
 * @date 2022/6/16 11:18
 */
public interface Client {
    /**
     * 开启连接
     */
    void open();
    /**
     * 发送消息
     */
    void send(Packet packet);
    /**
     * 关闭客户端连接
     */
    void close();
    /**
     * 获取连接目标的远程地址
     */
    HostAndPort getTargetRemote();

    static Client get(HostAndPort hostAndPort){
        return ClientFactory.CLIENT_MAP.get(hostAndPort);
    }

    class ClientFactory{
        private static final Map<HostAndPort,Client> CLIENT_MAP = new ConcurrentHashMap<>();
        protected static void add(Client client){
            CLIENT_MAP.put(client.getTargetRemote(),client);
        }
        protected static void remove(Client client){
            CLIENT_MAP.remove(client.getTargetRemote());
        }

        static {
            ShutdownManager.addShutdown(()-> CLIENT_MAP.values().forEach(Client::close));
        }
    }


}
